import 'dart:async';
import 'dart:convert' as convert;
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import 'Settings.dart';

class WebSocketUtil{
  WebSocketUtil._internal();
  factory WebSocketUtil()=>_instance;
  static final WebSocketUtil _instance = WebSocketUtil._internal();
  static WebSocketUtil getInstance(){
    return _instance;
  }


  late IOWebSocketChannel _webSocket; // WebSocket
  final int _heartTimes = 5000; // 心跳间隔(毫秒),重连间隔
  late Function onError; // 连接错误回调
  late Function onOpen; // 连接开启回调
  late Function onMessage; // 接收消息回调


  void initWebSocket({required Function onOpen, required Function onMessage, required Function onError}) {
    this.onOpen = onOpen;
    this.onMessage = onMessage;
    this.onError = onError;
    openSocket();
  }

  /// 开启WebSocket连接
  void openSocket() {
    _webSocket = IOWebSocketChannel.connect(Settings.websocket);
    // print('WebSocket连接成功: ${Settings.websocket}');
    onOpen();
    // 接收消息
    _webSocket.stream.listen((data) => webSocketOnMessage(data),onError: webSocketOnError, onDone: webSocketOnDone);
  }

  /// WebSocket接收消息回调
  webSocketOnMessage(data) {
    onMessage(data);
  }

  /// WebSocket关闭连接回调
  webSocketOnDone() {
    // print('closed');
    reconnect();
  }

  /// WebSocket连接错误回调
  webSocketOnError(e) {
    // print("error");
    WebSocketChannelException ex = e;
    onError(ex.message);
    closeSocket();
  }

  ///链接时身份验证
  void authentication(token,empNo){
    Map request = {};
    request["empNo"] = empNo;
    _webSocket.sink.add(convert.jsonEncode(request));
  }

  /// 关闭WebSocket
  void closeSocket() {
    // print('WebSocket连接关闭');
    _webSocket.sink.close();
  }

  /// 重连机制
  void reconnect() {
    Future.delayed(const Duration(milliseconds: 5000), () {
      openSocket();
    });
  }
}